package com.demo.forum.services.impl;

import com.demo.forum.common.Result;
import com.demo.forum.common.ResultCode;
import com.demo.forum.dao.UserMapper;
import com.demo.forum.model.User;
import com.demo.forum.model.exception.ApplicationException;
import com.demo.forum.services.IUserService;
import com.demo.forum.utils.MD5Utils;
import com.demo.forum.utils.StringUtil;
import com.demo.forum.utils.UUIDUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        //参数校验
        if(user == null || StringUtil.isEmpty(user.getUsername())
        || StringUtil.isEmpty(user.getNickname())
        || StringUtil.isEmpty(user.getPassword())
        || StringUtil.isEmpty(user.getSalt())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }
        User userExit = userMapper.selectByUserName(user.getUsername());
        if(userExit !=  null){
            log.warn(ResultCode.AILED_USER_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.AILED_USER_EXISTS));
        }
        // 3. 新增用户流程,设备默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //插入数据
        int row = userMapper.insertSelective(user);
        if(row!=1){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功" + "username = "+user.getUsername() );


    }

    @Override
    public User selectByUserName(@NonNull String username) {

        return userMapper.selectByUserName(username);

    }

    @Override
    public User login( @NonNull String username, @NonNull String password) {
        User user = selectByUserName(username);
        if(user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 4. 对密码做校验
        String encryptPassword = MD5Utils.md5Salt(password, user.getSalt());
        // 5. 用密文和数据库中存的用户密码进行比较
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", 密码错误, username = " + username);
            // 抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_LOGIN));
        }
        // 打印登录成功的日志
        log.info("登录成功, username = " + username);
        // 登录成功，返回用户信息

        return user;

    }

    @Override
    public User selectById(Long id) {
       if(id == null){
           log.warn(ResultCode.FAILED_FORBIDDEN.toString());
           throw new ApplicationException(Result.failed(ResultCode.FAILED_FORBIDDEN));

       }
        User user = userMapper.selectByPrimaryKey(id);
       if(user == null ){
           log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
           throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));

       }

       return user;

    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_IS_NULL));
        }

       User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed
                    (ResultCode.FAILED_USER_NOT_EXISTS)
                    +", id =  "+id);
        }
      User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //参数校验
        if(id== null || id <= 0){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_IS_NULL));
        }
        User user = userMapper.selectByPrimaryKey(id);
        //判断 user 状态
        if(user == null || user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS)
                    +", user id =  "+id);
        }
        //更新用户信息
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setArticleCount(user.getArticleCount()-1);
        if(updateUser.getArticleCount() < 0){
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }


    }

    @Override
    public void modifyInfo(User user) {
        //参数判断
        if(user == null || user.getId() ==  null || user.getId() <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User exitUser = userMapper.selectByPrimaryKey(user.getId());
        if(exitUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 定义一个标志位
        boolean checkAttr = false; // false表示没有校验通过

        User updateUser = new User();
        updateUser.setId(user.getId());
        if(!StringUtil.isEmpty(user.getUsername())
          && !user.getUsername().equals(exitUser.getUsername())){
            //看看数据库中有没有这个用户名(项目要求不能重名)

            User user1 = userMapper.selectByUserName(user.getUsername());
            if(user1 != null){
                log.warn(ResultCode.AILED_USER_EXISTS.toString());
                throw new ApplicationException(Result.failed(ResultCode.AILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr = true;
        }
        //昵称
        if(!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(exitUser.getNickname())){

            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }
        //电话号码
        if(!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(exitUser.getPhoneNum())){

            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }

        //邮箱
        if(!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(exitUser.getEmail())){

            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }

        //个人简介
        if(!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(exitUser.getRemark())){

            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }
        //性别

        if(user.getGender()!= null && user.getGender() != exitUser.getGender()){

            updateUser.setGender(user.getGender());
            if(updateUser.getGender() < 0 ||updateUser.getGender() >2){
                updateUser.setGender((byte) 2);
            }
            checkAttr = true;
        }

        if(checkAttr == false) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            throw new ApplicationException("两个修改内容相同,请重新输入");
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //1.参数校验
        if(id == null || id<= 0 || StringUtil.isEmpty(newPassword)
                || StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断用户状态
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null ||user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验原密码是否正确

        String oldEncruptPassword = MD5Utils.md5Salt(oldPassword,user.getSalt());
        if(!oldEncruptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置新密码
        String salt = UUIDUtil.UUID_32(); //密文
        String encruptPassword = MD5Utils.md5Salt(newPassword,salt);
        //封装对象
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setSalt(salt);
        updateUser.setPassword(encruptPassword);
        updateUser.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString()+" , 受影响行数不为1!");
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }


    }

}
